import ReactDOM from 'react-dom'
import './index.css'
import Tabs from './components/Tabs'
import Form from './components/Form'
import List from './components/List'
import { Component } from 'react'

class App extends Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot',
      },
      {
        id: 2,
        name: '时间',
        type: 'time',
      },
    ],
    active: 'hot',
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: new Date('2020-12-10 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1,
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '哎哟，不错哦',
        time: new Date('2020-10-11 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0,
      },
      {
        id: 3,
        author: '五月天',
        comment: '不打扰，是我的温柔',
        time: new Date('2021-08-11 10:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1,
      },
    ],
  }
  // 1.tabs 改变高亮状态
  changeActive = (type) => {
    this.setState({
      active: type,
    })
  }
  // 2.点击form组件中的赞或踩 子传父
  changeAttitude = (id, type) => {
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          return { ...item, attitude: type }
        }
        return item
      }),
    })
  }
  // 3.删除
  del = (id) => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }
  // 4.添加评论
  add = (content) => {
    const newObj = {
      id: Date.now(),
      author: 'wulihaha',
      comment: content,
      time: new Date().toLocaleString(),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 0,
    }
    this.setState({
      list: [...this.state.list, newObj],
    })
  }
  render() {
    const { list, tabs, active } = this.state
    return (
      <div className="App">
        <div className="comment-container">
          {/* 评论数 */}
          <div className="comment-head">
            <span>{list.length} 评论</span>
          </div>
          {/* 排序 */}
          <Tabs
            tabs={tabs}
            active={active}
            changeActive={this.changeActive}
          ></Tabs>
          {/* 添加评论 */}
          <Form add={this.add}></Form>
          {/* 评论列表 */}
          <List
            list={list}
            changeAttitude={this.changeAttitude}
            del={this.del}
            active={active}
          ></List>
        </div>
      </div>
    )
  }
  // 存储到本地
  componentDidUpdate() {
    localStorage.setItem('list', JSON.stringify(this.state.list))
  }
  // 首先从本地存储中获取数据
  componentDidMount() {
    const list = JSON.parse(localStorage.getItem('list')) || []
    this.setState({ list })
  }
}

ReactDOM.render(<App></App>, document.getElementById('root'))
